package com.jt.assistant.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.jt.assistant.R
import com.jt.assistant.adapter.HomeAdapter
import com.jt.assistant.bean.AppInfo
import com.jt.assistant.bean.HomeBean
import com.jt.assistant.bean.UpdateAppBean
import com.jt.assistant.utils.NumberUtil
import com.jt.assistant.viewmodel.LoginViewModel
import com.jt.assistant.base.GlobalConfig
import com.open.hule.library.entity.AppUpdate
import com.open.hule.library.utils.UpdateManager
import com.orhanobut.logger.Logger
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.request.ExplainScope
import com.tencent.mmkv.MMKV
import com.yzp.mvvmlibrary.base.BaseActivity
import com.yzp.mvvmlibrary.base.MessageEvent
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.activity_home.rv_home
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import kotlin.collections.ArrayList

/**
 * 主界面
 */
class HomeActivity : BaseActivity<LoginViewModel>() {
    private var data = ArrayList<HomeBean>()
    private var mTextToSpeech: TextToSpeech? = null
    private val mAdapter by lazy {
        HomeAdapter(
            ArrayList<HomeBean>()
        )
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    override fun layoutId(): Int = R.layout.activity_home

    override fun initView(savedInstanceState: Bundle?) {
        with(rv_home) {
            layoutManager = GridLayoutManager(context, 3)
            adapter = mAdapter
        }
        EventBus.getDefault().register(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        tv_name.text = MMKV.defaultMMKV().getString("NAME", "").toString() + " , 欢迎使用"
        getHomeData()
        mAdapter.data.addAll(data)
        mAdapter.notifyDataSetChanged()
        initSpeech()
        bestPermissionX()
        viewModel.getUpgradeUlr()
    }

    override fun initListener() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
            startActivity(Intent(this, mAdapter.data[position].aClass))
        }

        viewModel.mGetUpgradeUlrValue.observe(this, androidx.lifecycle.Observer {
            Logger.e(GsonUtils.toJson(it))

            if (it.isSuccess())
                viewModel.getUpgrade(
                    "http://40.73.59.226:9001" + it.data.url,
                    AppInfo(
                        AppUtils.getAppPackageName(),
                        AppUtils.getAppVersionCode().toString(),
                        DeviceUtils.getMacAddress().toString()
                    )
                )
        })

        viewModel.mGetUpgradeValue.observe(this, androidx.lifecycle.Observer {
            if (it.isSuccess())
                update(it.data)

        })
    }

    private fun update(data: UpdateAppBean) {
        //http://40.73.59.226:1889/api/apk/d8e14db8fa0d4724a64217e0098bc29e.apk
        Logger.e("http://40.73.59.226:9001" + data.upgradeUrl)
        // 更新的数据参数
        val appUpdate = AppUpdate.Builder()
            .newVersionUrl("http://40.73.59.226:9001" + data.upgradeUrl)
            .newVersionCode(data.versionName + " : " + data.versionCode)
            .updateResourceId(R.layout.dialog_update)
            .updateTitle(R.string.update_title)
            .updateContentTitle(R.string.update_content_lb)
            .updateInfo(data.upgradeMsg.replace(" ", "\n"))
            .md5(data.md5)
            .isSilentMode(false)
            .updateProgressColor(Color.BLUE)
            .build()
        UpdateManager().startUpdate(this, appUpdate)
    }


    private fun initSpeech() {
        mTextToSpeech = TextToSpeech(
            applicationContext
        ) { status ->
            if (status == TextToSpeech.SUCCESS) {
                val result: Int = mTextToSpeech!!.setLanguage(Locale.CHINA)
                if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED
                ) {
                    ToastUtils.showShort("请升级语音引擎,详情请联系管理员")
                }
            }
        }
        mTextToSpeech!!.setPitch(1.0f)
        mTextToSpeech!!.setSpeechRate(1.4f)
    }


    private fun speak(text: String?) {
        if (mTextToSpeech != null) {
            mTextToSpeech!!.stop()
            mTextToSpeech!!.speak(text, TextToSpeech.QUEUE_FLUSH, null)
            ToastUtils.showShort(text)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun message(messageEvent: MessageEvent) {
        if (messageEvent.type === GlobalConfig.MSG_SPEAK) {
            speak(messageEvent.msg)
            ToastUtils.showShort(messageEvent.msg)
        }
    }

    private fun bestPermissionX() {
        PermissionX.init(this)
            .permissions(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA
            )
            .setDialogTintColor(Color.parseColor("#008577"), Color.parseColor("#83e8dd"))
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String?>? ->
                val message = "需要您同意以下权限才能正常使用"
                scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
            }
            .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?> ->
                if (allGranted) {
                } else {
                    Toast.makeText(this, "您拒绝了如下权限：$deniedList", Toast.LENGTH_SHORT).show()
                }
            }
    }


    private fun getHomeData() {
        data.add(
            HomeBean(
                "送仓扫码",
                R.mipmap.menu_item_icon_delivery_batch_up,
                ScanHomeActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "快捷转运",
                R.mipmap.menu_item_icon_delivery_recheck_up,
                FastTransferActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "运单修改",
                R.mipmap.menu_item_icon_collect_up,
                WaybillActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "单据上报",
                R.mipmap.menu_item_icon_collect_stock_up,
                ReceiptsUploadActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "箱码补打",
                R.mipmap.menu_item_icon_openload_up,
                PrinterActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "退货封箱",
                R.mipmap.menu_item_icon_loadbox_up,
                SealHomeActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "退仓扫码",
                R.mipmap.menu_item_icon_move_batch_up,
                ReturnScanHomeActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "SKU上传",
                R.mipmap.menu_item_icon_shelve_up,
                SkuPicActivity::class.java
            )
        )
        data.add(
            HomeBean(
                "设置",
                R.mipmap.menu_item_icon_accept_quick_up,
                SettingActivity::class.java
            )
        )
    }

}